//
//  HMPhotoSelectorController.swift
//  76.照片选择器
//
//  Created by shenzhenIOS on 16/4/21.
//  Copyright © 2016年 shenzhenIOS. All rights reserved.
//

import UIKit

import HMImagePicker

private let reuseIdentifier = "Cell"

class HMPhotoSelectorController: UICollectionViewController {
    
    // 记录用户选择的图片
    var photos = [UIImage]()
    
    private var selectedAssets: [PHAsset]?
    
    private var maxCount = 6
    
    private var layout = UICollectionViewFlowLayout()
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    init() {
        super.init(collectionViewLayout: layout)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        layout.itemSize = CGSize(width: 80, height: 80)
        self.collectionView?.registerClass(HMPhotoSelectorCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        self.collectionView?.backgroundColor = UIColor.whiteColor()
        self.collectionView?.contentInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
    }

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // 当图片没有到最大张数时,显示图片和一个加号按钮
        // 当图片的数量到达最大张数时,显示的是最大张数
        return photos.count < maxCount ? photos.count + 1 : photos.count
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! HMPhotoSelectorCell
        
        cell.backgroundColor = UIColor.brownColor()
        
        // 将图片设置给cell
        
        // 5.设置代理
        cell.delegate = self
        
        if indexPath.item < photos.count {
            cell.image = photos[indexPath.item]
        } else {
            // 加号按钮
            cell.setupAddButton()
        }
    
        return cell
    }
}

// 6.实现代理
extension HMPhotoSelectorController: HMPhotoSelectorCellDelegate {
    /// 删除按钮被点击的代理
    func photoSelectorCellDidClickDeleteButton(cell: HMPhotoSelectorCell) {
        // 获取cell的indexPath
        let indexPath = collectionView?.indexPathForCell(cell)
        // 删除图片
        photos.removeAtIndex(indexPath!.item)
        
        self.selectedAssets?.removeAtIndex(indexPath!.item)
        
        // 刷新数据
        collectionView?.reloadData()
    }
    
    /// 加号按钮被点击的代理
    func photoSelectorCellDidClickAddButton(cell: HMPhotoSelectorCell) {
//        print("photoSelectorCellDidClickAddButton: \(cell)")
        
//        // 系统有一个照片选择器
//        let pickerVC = UIImagePickerController()
//        
//        // protocol<UIImagePickerControllerDelegate, UINavigationControllerDelegate>
//        // 必须同时实现2个协议
//        pickerVC.delegate = self
//        
//        presentViewController(pickerVC, animated: true, completion: nil)
        
        // 使用第三方
//        // 设置图像选择代理
//        picker.pickerDelegate = self;
//        // 设置目标图片尺寸
//        picker.targetSize = CGSizeMake(600, 600);
//        // 设置最大选择照片数量
//        picker.maxPickerCount = 9;
//        
//        [self presentViewController:picker animated:YES completion:nil];
        let picker = HMImagePickerController(selectedAssets: selectedAssets)
        picker.pickerDelegate = self
        // 设置目标图片尺寸
        picker.targetSize = CGSizeMake(600, 600)
        // 设置最大选择照片数量
        picker.maxPickerCount = 6
        presentViewController(picker, animated: true, completion: nil)
    }
}

// 实现黑马选择器的代理
extension HMPhotoSelectorController: HMImagePickerControllerDelegate {
    func imagePickerController(picker: HMImagePickerController, didFinishSelectedImages images: [UIImage], selectedAssets: [PHAsset]?) {
        self.photos = images
        self.selectedAssets = selectedAssets
        
        collectionView?.reloadData()
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
}

// 让控制器同时实现 UIImagePickerControllerDelegate 和 UINavigationControllerDelegate
extension HMPhotoSelectorController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    // 当选中图片就会调用这个代理方法
    // 当实现这个代理协议,需要我们自己来关闭控制器
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
//        print("image: \(image)")
        
        // 等比例缩小,宽度缩小到300
        // newHeight / newWidth = oldHeight / oldWidth
        let newWidht: CGFloat = 300
        let newHeight = newWidht * image.size.height / image.size.width
        
        // 将图片缩小
        image.hm_AsyncDrawImage(CGSize(width: newWidht, height: newHeight)) { (image) -> () in
            // 绘制好得图片
            self.photos.append(image)
            
            // 刷新数据
            self.collectionView?.reloadData()
            
            // 关闭控制器
            picker.dismissViewControllerAnimated(true, completion: nil)
        }
    }
}

// ---------- cell 相关---------
// 1.定义代理协议
protocol HMPhotoSelectorCellDelegate: NSObjectProtocol {
    // 2.定义协议方法
    /// 加号按钮被点击
    func photoSelectorCellDidClickAddButton(cell: HMPhotoSelectorCell)
    
    /// 删除按钮被点击
    func photoSelectorCellDidClickDeleteButton(cell: HMPhotoSelectorCell)
}

class HMPhotoSelectorCell: UICollectionViewCell {
    
    /// cell要显示的图片
    var image: UIImage? {
        didSet {
            // 将图片设置给加号按钮
            addButton.setImage(image, forState: UIControlState.Normal)
            
            // 显示删除按钮
            deleteButton.hidden = false
        }
    }
    
    // 设置加号按钮
    func setupAddButton() {
        addButton.setImage(UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
        
        // 隐藏删除按钮
        deleteButton.hidden = true
    }
    
    /// 3.定义代理属性
    weak var delegate: HMPhotoSelectorCellDelegate?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        preapreUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func preapreUI() {
        // 添加控件
        contentView.addSubview(addButton)
        contentView.addSubview(deleteButton)
        
        // 添加约束
        addButton.translatesAutoresizingMaskIntoConstraints = false
        deleteButton.translatesAutoresizingMaskIntoConstraints = false
        
        // VFL
        // 加号按钮, 填充父控件
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[ab]-0-|", options: [], metrics: nil, views: ["ab" : addButton]))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[ab]-0-|", options: [], metrics: nil, views: ["ab" : addButton]))
        
        // 删除按钮, 父控件右上角
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[db]-0-|", options: [], metrics: nil, views: ["db" : deleteButton]))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[db]", options: [], metrics: nil, views: ["db" : deleteButton]))
    }
    
    // 删除按钮被点击
    @objc private func didClickDeleteButton() {
        // 4.调用代理
        delegate?.photoSelectorCellDidClickDeleteButton(self)
    }
    
    // 加号按钮被点击
    @objc private func didClickAddButton() {
        // 4.调用代理
        delegate?.photoSelectorCellDidClickAddButton(self)
    }
    
    // MARK: - 懒加载
    /// 删除按钮
    private lazy var deleteButton: UIButton = {
        let button = UIButton()
        
        // 设置
        button.setImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Normal)
        button.addTarget(self, action: Selector("didClickDeleteButton"), forControlEvents: UIControlEvents.TouchUpInside)
        
        return button
    }()
    
    /// 加号按钮,可以显示图片
    private lazy var addButton: UIButton = {
        let button = UIButton()
        
        // 设置
        button.setImage(UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
//        button.setImage(UIImage(named: "compose_pic_add_highlighted"), forState: UIControlState.Highlighted)
        
        // 设置按钮图片的填充模式
        button.imageView?.contentMode = UIViewContentMode.ScaleAspectFill
        
        button.addTarget(self, action: Selector("didClickAddButton"), forControlEvents: UIControlEvents.TouchUpInside)
        
        return button
    }()
}